
import { _decorator, Component, Node, RigidBody2D, ERigidBody2DType, PolygonCollider2D, v2 } from 'cc';
import GameData from '../../Script/Common/GameData';
import yyComponent from '../../Script/Common/yyComponent';
import GameConfig from '../../Script/GameSpecial/GameConfig';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
const { ccclass, property } = _decorator;

@ccclass('Map')
export class Map extends yyComponent {

    public init() {
        let n = this.node.name;
        let data = GameData.getData(GlobalEnum.GameDataType.MapData, n);
        this.createRigidNode(data.collider);
    }

    public reuse() {
        this.enableRigidNode();
    }
    public unuse() {
        this.disableRigidNode();
    }

    /*****************************************对外功能*****************************************/
    /**激活碰撞体替身 */
    public enableRigidNode() {
        let rate = GameConfig.GameRule.rate3to2;
        this.rigidNode.setPosition(this.node.position.x * rate, -this.node.position.z * rate, 0);
        this.emit(EventType.LevelEvent.addRigidNode, this.rigidNode);
    }
    /**禁用碰撞体替身 */
    public disableRigidNode() {
        if (!!this.rigidNode) {
            this.rigidNode.removeFromParent();
        }
    }

    //#region 碰撞体
    /**用于2d物理引擎计算的2d物理刚体节点 */
    protected rigidNode: Node = null;
    protected rigidNodes: Node[] = [];
    /**在2D物理世界生成一个碰撞体替身 */
    protected createRigidNode(data) {
        if (!!this.rigidNode) return;
        //碰撞体节点
        let node = new Node();
        this.rigidNode = node;
        // this.rigidNodes.push(node);
        //刚体组件
        let rigid = node.addComponent(RigidBody2D);
        let group = GlobalEnum.RigidGroup.ground;
        rigid.group = group;
        rigid.enabledContactListener = false;
        rigid.bullet = false;
        rigid.type = ERigidBody2DType.Static;
        rigid.allowSleep = true;
        let rate = GameConfig.GameRule.rate3to2;
        // rate = 10;
        for (let i = 0, c = data.length; i < c; ++i) {
            //碰撞体形状
            let collider = node.addComponent(PolygonCollider2D);
            collider.tag = 0;
            collider.group = group;
            collider.sensor = false;
            collider.friction = 0;
            collider.restitution = 0;
            collider.offset = v2(0, 0);
            let points = data[i];
            let arr = [];
            for (let index = 0, count = points.length; index < count; index += 2) {
                arr.push(v2(points[index] * rate, points[index + 1] * rate));
            }
            collider.points = arr;
        }
    }
    //#endregion

}
